package com.kaiyidiannao.activity.tour;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import com.kaiyi.diannao.net.AsyncHttpResponseParse;
import com.kaiyi.diannao.net.LoadDataHandler;
import com.kaiyi.diannao.net.RequestClient;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.AppUtils;
import com.kaiyidiannao.common.util.UploadImageUtils;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.imagescale.ImageGalleryActivity;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.TourBean;
import com.kaiyidiannao.view.ActionBarView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by david on 24/04/14.
 * 凑对去 - 微记发布 - 图片带剪裁的
 */
public class TourSmallNotePublishActivity_bak extends BaseActionBarActivity {

    private ImageView mImg0;
    private ImageView mImg1;
    private ImageView mImg2;
    private ImageView mImg3;
    private ImageView mImg4;
    private ImageView mImg5;
    private ImageView mImg6;
    private ImageView mImg7;

    private int mIndex = 0;

    private EditText tour_gather_publish_title;
    private EditText tour_gather_publish_introduce;
    private int[] cate_id = DataCenter.tour_category_id;

    String name;
    String introduce;

    private static final String IMAGE_FILE_NAME = "faceImage";
    private String[] mImagePaths = new String[8];
    private String[] items = new String[]{"选择本地图片", "拍照"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_small_note_publish);

        findActionBar();
        findViewById();
        initListener();
        initImageListener();

        //隐藏软键盘和功能选项
        AppUtils.setupUI(findViewById(R.id.scrollviewsmallnote), this);
    }


    private void findViewById() {

        tour_gather_publish_title = (EditText) findViewById(R.id.tour_gather_publish_title);
        tour_gather_publish_introduce = (EditText) findViewById(R.id.tour_gather_publish_introduce);

        mImg0 = (ImageView) findViewById(R.id.auction_upload_imageView);
        mImg1 = (ImageView) findViewById(R.id.auction_upload_imageView1);
        mImg2 = (ImageView) findViewById(R.id.auction_upload_imageView2);
        mImg3 = (ImageView) findViewById(R.id.auction_upload_imageView3);
        mImg4 = (ImageView) findViewById(R.id.auction_upload_imageView4);
        mImg5 = (ImageView) findViewById(R.id.auction_upload_imageView5);
        mImg6 = (ImageView) findViewById(R.id.auction_upload_imageView6);
        mImg7 = (ImageView) findViewById(R.id.auction_upload_imageView7);

        Intent intent = getIntent();

        if (intent.getStringExtra("flag") == null) {

        } else {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                TourBean tourBean = (TourBean) bundle.getSerializable("tourBeanSmall");
                tour_gather_publish_title.setText(tourBean.getTitle());
                tour_gather_publish_introduce.setText(tourBean.getIntroduce());
            }
        }

    }

    private void initListener() {
        // 开始发送
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 开始提交商品###
                if (isLogin()) {
                    cheakUpdate();
                    return;
                } else {
                    startLoginOrRegistered();
                }
            }
        });
    }

    private void initImageListener() {
        mImg0.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 0;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 1;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 2;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 3;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg4.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 4;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg5.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 5;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg6.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 6;
                showDialogOrFullImage(mIndex);
            }
        });
        mImg7.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mIndex = 7;
                showDialogOrFullImage(mIndex);
            }
        });
    }

    private void cheakUpdate() {
        //名称
        name = tour_gather_publish_title.getText().toString();
        if (isEmpty(name)) {
            showToast("标题不能为空");
            tour_gather_publish_title.setFocusable(true);
            tour_gather_publish_title.requestFocus();
            return;
        }else if(name.trim().length()>10 || name.trim().length()<3){
            showToast("标题为3-10位");
            tour_gather_publish_title.setFocusable(true);
            tour_gather_publish_title.requestFocus();
            return;
        }

        //介绍
        introduce = tour_gather_publish_introduce.getText().toString();
        if (isEmpty(introduce)) {
            showToast("介绍不能为空");
            tour_gather_publish_introduce.setFocusable(true);
            tour_gather_publish_introduce.requestFocus();
            return;
        }else if(introduce.length()<12){
            showToast("介绍应为12~200字");
            tour_gather_publish_introduce.setFocusable(true);
            tour_gather_publish_introduce.requestFocus();
            return;
        }

        if (mImagePaths[0] != null && !"".equals(mImagePaths[0]) && new File(mImagePaths[0]).exists()) {
            // 开始上传图片
            uploadImages(0);
        } else {
            // ##可以上传了
            startUpLoadData();
        }

    }

    private boolean isEmpty(String str) {
        if (str != null && !"".equals(str.trim())) {
            return false;
        }
        return true;
    }


    // 时间选择器
    private void showCalendars(final TextView textView) {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(TourSmallNotePublishActivity_bak.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                textView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }

    // 上传图片
    private void showImageDialog() {
        new AlertDialog.Builder(this)
                .setTitle("上传图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                startActivityForResult(intentFromGallery, UploadImageUtils.IMAGE_REQUEST_CODE);
                                break;
                            case 1:
                                Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断存储卡是否可以用，可用进行存储
                                if (AppUtils.isExistSD()) {
                                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                                    File file = new File(path + "/" +IMAGE_FILE_NAME + mIndex + ".png");
                                    if( !file.exists() ) {
                                        file.getParentFile().mkdirs();
                                    }
                                    intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                                }
                                startActivityForResult(intentFromCapture,UploadImageUtils.CAMERA_REQUEST_CODE);
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();

    }

    private String savePhoto(Bundle bundle) {
        Bitmap bitmap;
        if (bundle != null) {
            bitmap = bundle.getParcelable("data");
        }else{
            return null;
        }

        FileOutputStream b = null;
        String pathPhoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/cache/";
        File file = new File(pathPhoto + IMAGE_FILE_NAME + mIndex + ".png");
        if(!file.exists()) {
            file.getParentFile().mkdirs();// 创建文件夹
        }
        try {
            b = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if( b!=null ) {
                    b.flush();
                    b.close();
                }
                return file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //结果码不等于取消时候
        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case UploadImageUtils.IMAGE_REQUEST_CODE:
                    UploadImageUtils.startPhotoZoom(TourSmallNotePublishActivity_bak.this, data.getData());
                    break;
                case UploadImageUtils.CAMERA_REQUEST_CODE:
                    if (AppUtils.isExistSD()) {
                        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                        File tempFile = new File(path + "/" +IMAGE_FILE_NAME + mIndex + ".png");
                        UploadImageUtils.startPhotoZoom(TourSmallNotePublishActivity_bak.this, Uri.fromFile(tempFile));
                    } else {
                        Toast.makeText(TourSmallNotePublishActivity_bak.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
                    }
                    break;
                case UploadImageUtils.RESULT_REQUEST_CODE: //图片缩放完成后
                    if (data != null) {
                        // 保存图片
                        mImagePaths[mIndex] = savePhoto(data.getExtras());
                        if( mImagePaths[mIndex] == null ) {
                            Toast.makeText(this, "图片转换出错", Toast.LENGTH_SHORT).show();
                        }

                        Drawable drawable = UploadImageUtils.getImageToView(data, TourSmallNotePublishActivity_bak.this);
                        switch (mIndex) {
                            case 0:
                                mImg0.setImageDrawable(drawable);
                                mImg1.setVisibility(View.VISIBLE);
                                break;
                            case 1:
                                mImg1.setImageDrawable(drawable);
                                mImg2.setVisibility(View.VISIBLE);
                                break;
                            case 2:
                                mImg2.setImageDrawable(drawable);
                                mImg3.setVisibility(View.VISIBLE);
                                break;
                            case 3:
                                mImg3.setImageDrawable(drawable);
                                mImg4.setVisibility(View.VISIBLE);
                                break;
                            case 4:
                                mImg4.setImageDrawable(drawable);
                                mImg5.setVisibility(View.VISIBLE);
                                break;
                            case 5:
                                mImg5.setImageDrawable(drawable);
                                mImg6.setVisibility(View.VISIBLE);
                                break;
                            case 6:
                                mImg6.setImageDrawable(drawable);
                                mImg7.setVisibility(View.VISIBLE);
                                break;
                            case 7:
                                mImg7.setImageDrawable(drawable);
                                break;
                            default:
                                break;
                        }
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("微记发布");

        // upload = (ImageView)findViewById(R.id.upload);

        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.positive_button));

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void startUpLoadData() {


        if (!isLogin()) {
            startLoginOrRegistered();
            return;
        }

        if (!HttpUtils.isConnected()) {
            closeProgressDialog();
            showToast(getString(R.string.no_network));
            return;
        }

        RequestParams params = new RequestParams();
        params.put("mid", "31");
        params.put("action", "add");
        params.put("userid", super.getUserid());
        params.put("post[catid]", cate_id[1] + "");
        params.put("post[title]", name);
        params.put("post[introduce]", introduce);

        for (int i = 0; i < mImagePaths.length; i++) {
            if (mImagePaths[i] != null && !"".equals(mImagePaths[i].trim())) {
                if (i == 0) {
                    params.put("post[thumb]", mImagePaths[i]);
                } else {
                    params.put("post[thumb" + i + "]", mImagePaths[i]);
                }
            }
        }

        System.out.println("params--->" + params.toString());

        RequestClient.post(this, "http://www.3tixa.com:8086/kaiyi/member/my.php", params, new AsyncHttpResponseHandler() {
            //192.168.29.135:8080
            //www.3tixa.com:8086
            @Override
            public void onStart() {
                showProgressDialog(getString(R.string.loading));
            }

            @Override
            public void onSuccess(String content) {
                if (!HttpUtils.isConnected()){
                    showToast(R.string.no_network);
                    return;
                }else {
                    Toast.makeText(TourSmallNotePublishActivity_bak.this, "发布成功", Toast.LENGTH_SHORT).show();
                    finish();
                    System.out.println("content-->" + content);
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                Toast.makeText(TourSmallNotePublishActivity_bak.this, "发布失败，请重试！", Toast.LENGTH_SHORT).show();
                return;
            }

            @Override
            public void onFinish() {
               closeProgressDialog();
            }

        });
    }

    private void uploadImages(final int pos) {

        if (!HttpUtils.isConnected()) {
            showToast(getString(R.string.no_network));
            closeProgressDialog();
            return;
        }

        RequestParams params = new RequestParams();
        params.put("moduleid", "31");

        try {
            params.put("upalbum", new File(mImagePaths[pos]));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//    	params.put("oldurl", values); 	// 需要判断

        RequestClient.post(this, "http://www.3tixa.com:8086/kaiyi/appupload.php", params, new AsyncHttpResponseParse(this, new LoadDataHandler() {

            @Override
            public void onStart() {
                showProgressDialog(getString(R.string.loading));
            }

            @Override
            public void onSuccess(String data) {
                if (data != null) {
                    mImagePaths[pos] = data.substring(2, data.length() - 2);
                    System.out.println(pos + ":" + data.substring(2, data.length() - 2));
                }
                // 提交成功, 提交下一个
                if (pos < mImagePaths.length - 1) {
                    if (mImagePaths[pos + 1] != null && !"".equals(mImagePaths[pos + 1])) {
                        uploadImages(pos + 1);
                    } else {
                        // 图片上传完毕
                        /***开始上传信息**/
                        startUpLoadData();
                    }
                } else {
                    // 图片上传完毕
                    /***开始上传信息**/
                    startUpLoadData();
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                // 失败重新提交
                if (HttpUtils.isConnected()) {
                    uploadImages(pos);
                } else {
                    showToast(getString(R.string.no_network));
                    closeProgressDialog();
                }
            }

        }));
    }


    /**
     * 显示图片选择对话框，或者全屏浏览图片
     * @param mIndex
     */
    private void showDialogOrFullImage(int mIndex) {
        if (mImagePaths == null || mImagePaths[mIndex] == null || TextUtils.isEmpty(mImagePaths[mIndex].trim())) {
            showImageDialog();
        } else {
            startFullImage(mIndex);
        }
    }

    /**
     * 开启全屏图片浏览
     * @param defaultIndex
     */
    private void startFullImage(int defaultIndex) {
        Intent intent = new Intent(TourSmallNotePublishActivity_bak.this, ImageGalleryActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("defaultIndex", defaultIndex);
        ArrayList<String> imgPaths = new ArrayList<String>();
        for (String path : mImagePaths) {
            if (!TextUtils.isEmpty(path)) {
                imgPaths.add(path);
            }
        }
        bundle.putStringArrayList("imgPaths", imgPaths);
        intent.putExtras(bundle);
        startActivity(intent);
    }

}
